<style lang="less">
    @import "./common.less";
</style>
<template>
    <div>
        <Modal fullscreen title="新建预约" v-model="iModal" scrollable ok-text="保存" :loading="modalLoading" @on-ok="save">
            <Card title="预约设置">
                <Form :model="siteData" :label-width="90">
                    <FormItem label="预约名称">
                        <Input v-model="siteData.name" placeholder="请输入预约名称"></Input>
                    </FormItem>
                    <FormItem label="简介">
                        <Input v-model="siteData.desc" placeholder="请输入预约简介"></Input>
                    </FormItem>
                    <FormItem label="提示信息">
                        <Input v-model="siteData.note" type="textarea" :autosize="{maxRows: 255}" :rows="4"
                               placeholder="提示信息"/>
                    </FormItem>
                    <FormItem label="尾部提示">
                        <Input v-model="siteData.address" placeholder="请输入预约场地地址"></Input>
                    </FormItem>
                    <FormItem label="是否开启">
                        <i-switch v-model="siteData.switch" size="large">
                            <span slot="open">开启</span>
                            <span slot="close">关闭</span>
                        </i-switch>
                    </FormItem>
                    <FormItem label="预约场地图片">
                        <div class="demo-upload-list" v-for="item in uploadList">
                            <template v-if="item.status === 'finished'">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleImgView(item.name)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleImgRemove(item)"></Icon>
                                </div>
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                        </div>
                        <Upload
                            ref="upload"
                            :show-upload-list="false"
                            :on-success="handleImgSuccess"
                            :format="['jpg','jpeg','png']"
                            :max-size="20480"
                            :on-format-error="handleImgFormatError"
                            :on-exceeded-size="handleImgMaxSize"
                            :before-upload="handleImgBeforeUpload"
                            multiple
                            type="drag"
                            name="image"
                            :action="baseUrl+'upload/img'"
                            style="display: inline-block;width:58px;">
                            <div style="width: 58px;height:58px;line-height: 58px;">
                                <Icon type="ios-camera" size="20"></Icon>
                            </div>
                        </Upload>
                        <Modal title="查看" v-model="visible" z-index="999999">
                            <img :src="imgName" v-if="visible" style="width: 100%">
                        </Modal>
                    </FormItem>
                    <FormItem label="是否必须上传附件图片">
                        <i-switch v-model="siteData.is_need_annex" size="large">
                            <span slot="open">是</span>
                            <span slot="close">否</span>
                        </i-switch>
                    </FormItem>
                    <Upload :action="this.$config.baseUrl.pro+'upload/file'"
                            name="file"
                            ref="file"
                            :format="['doc','docx','xls','xlsx','pdf','txt','rar','zip']"
                            :max-size="2048"
                            :on-format-error="handleFileFormatError"
                            :on-exceeded-size="handleFileMaxSize"
                            :before-upload="handleFileBeforeUpload"
                            :on-remove="handleFileRemove"
                            :on-preview="handleFilePreview"
                    >
                        <Button icon="ios-cloud-upload-outline">上传附件</Button>
                    </Upload>
                </Form>
            </Card>
            <Card title="每天预约时间选项" class="margin-top-10">
                <a href="#" slot="extra">
                    本选项为每天可选时间段，目前未做时间合法性校验，请正确选择时间
                </a>
                <Form :label-width="90">
                    <div v-for="(item, index) in siteData.time" :key="index">
                        <FormItem :label="item.name">
                            <Col span="12">
                                <TimePicker v-model="item.time" format="HH:mm" confirm type="timerange"
                                            placement="bottom-end"
                                            placeholder="请选择时间区间" style="width: 200px"></TimePicker>
                            </Col>
                            <Col span="4">
                                <Button @click="handleTimeRemove(index)">Delete</Button>
                            </Col>
                        </FormItem>
                    </div>
                    <Button @click="addOptions">添加选项</Button>
                </Form>
            </Card>
            <Card title="上传需填入的表单信息（上传前请先下载模版）" class="margin-top-10">
                <a href="#" slot="extra">
                    input为单行输入框，phone为电话号码,testarea为文本框<span style="color: red">（修改时若不修改此项则无需上传）</span>
                </a>
                <Row type="flex" justify="start" class="code-row-bg">
                    <Col span="4">
                        <Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx"
                                style="width: 100px;">
                            <Button icon="ios-cloud-upload-outline" :loading="uploadLoading" @click="handleUploadFile">
                                上传文件
                            </Button>
                        </Upload>
                    </Col>
                    <Col span="4">
                        <Button icon="ios-cloud-download-outline" type="info" to="/back/download/demo.xlsx"
                                target="_blank"
                                class="margin-left-10">下载模版
                        </Button>
                    </Col>
                </Row>
                <Row>
                    <div class="ivu-upload-list-file" v-if="file !== null">
                        <Icon type="ios-stats"></Icon>
                        {{ file.name }}
                        <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove"
                              @click.native="handleRemove()"></Icon>
                    </div>
                </Row>
                <Row>
                    <transition name="fade">
                        <Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
                            <div v-if="progressPercent === 100">
                                <Icon type="ios-checkmark-circle"></Icon>
                                <span>成功</span>
                            </div>
                        </Progress>
                    </transition>
                </Row>
                <Row class="margin-top-10">
                    <Table :columns="tableTitle" :data="tableData" :loading="loading"></Table>
                </Row>
            </Card>
        </Modal>
    </div>
</template>
<script>
    import excel from '@/libs/excel'
    import config from '@/config'
    import {saveSite, getMySite} from '../../api/manager'

    export default {
        name: 'bookingsetting',
        props: {
            modal: false
        },
        data() {
            return {
                iModal: false,
                uploadLoading: false,
                progressPercent: 0,
                showProgress: false,
                showRemoveFile: false,
                file: null,
                tableData: [],
                tableTitle: [],
                tableLoading: false,
                siteData: {
                    id: null,
                    type: 'new',
                    time: [
                        {time: ["00:00", "00:00"], name: '选项1'}
                    ]
                },
                imgName: '',
                visible: false,
                uploadList: [],
                baseUrl: '',
                loading: false,
                modalLoading:true
            }
        },
        methods: {
            initUpload() {
                this.file = null
                this.showProgress = false
                this.loadingProgress = 0
                this.tableData = []
                this.tableTitle = []
            },
            handleUploadFile() {
                this.initUpload()
            },
            handleRemove() {
                this.initUpload()
                this.$Message.info('上传的文件已删除！')
            },
            handleBeforeUpload(file) {
                const fileExt = file.name.split('.').pop().toLocaleLowerCase()
                if (fileExt === 'xlsx' || fileExt === 'xls') {
                    this.readFile(file)
                    this.file = file
                } else {
                    this.$Notice.warning({
                        title: '文件类型错误',
                        desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
                    })
                }
                return false
            },
            handleFileFormatError(file) {
                this.$Notice.warning({
                    title: '文件格式错误',
                    desc: '文件名' + file.name + '错误,请选择doc,docx,xls,xlsx,pdf,txt,rar,zip文件'
                });
            },
            handleFileMaxSize(file) {
                this.$Notice.warning({
                    title: '文件大小超出限制',
                    desc: '文件' + file.name + '有点大，不能超过20M哦'
                });
            },
            handleFileBeforeUpload() {
                const check = this.$refs.file.fileList.length < 10;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多上传10个文件'
                    });
                }
                return check;
            },
            handleFileRemove(file,fileList){
                // console.log(this.annex)
                // console.log(file)
                // console.log(fileList)
            },
            handleFilePreview(file){
                window.open(this.$config.baseUrl.pro+"upload/"+file.response.data,'_blank')
            },
            // 读取文件
            readFile(file) {
                const reader = new FileReader()
                reader.readAsArrayBuffer(file)
                reader.onloadstart = e => {
                    this.uploadLoading = true
                    this.tableLoading = true
                    this.showProgress = true
                }
                reader.onprogress = e => {
                    this.progressPercent = Math.round(e.loaded / e.total * 100)
                }
                reader.onerror = e => {
                    this.$Message.error('文件读取出错')
                }
                reader.onload = e => {
                    this.$Message.info('文件读取成功')
                    const data = e.target.result
                    const {header, results} = excel.read(data, 'array')
                    const tableTitle = header.map(item => {
                        return {title: item, key: item}
                    })
                    this.tableData = results
                    this.tableTitle = tableTitle
                    this.uploadLoading = false
                    this.tableLoading = false
                    this.showRemoveFile = true
                }
            },
            handleImgView(name) {
                this.imgName = this.baseUrl + 'upload/' + name;
                if (name.toString().indexOf("http") !== -1) {
                    this.imgName = name;
                }
                window.open(this.imgName, '_blank')
                // this.visible = true;
            },
            handleImgRemove(file) {
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            },
            handleImgSuccess(res, file) {
                console.log(res)
                console.log(file)
                file.url = '/back/upload/' + res.data;
                file.name = res.data;
                // this.uploadList.push(file)
            },
            handleImgFormatError(file) {
                this.$Notice.warning({
                    title: '文件格式错误',
                    desc: '文件名' + file.name + '错误,请选择jpg,png,jpeg文件'
                });
            },
            handleImgMaxSize(file) {
                this.$Notice.warning({
                    title: '文件大小超出限制',
                    desc: '文件' + file.name + '有点大，不能超过20M哦'
                });
            },
            handleImgBeforeUpload() {
                const check = this.uploadList.length < 1;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多上传一张图片'
                    });
                }
                return check;
            },
            addOptions() {
                this.siteData.time.push({
                    time: [],
                    name: '选项' + (this.siteData.time.length + 1)
                })
            },
            handleTimeRemove(index) {
                let time = []
                for (let i in this.siteData.time) {
                    if (parseInt(i) !== index)
                        time.push({
                            time: this.siteData.time[i].time,
                            name: '选项' + (time.length + 1)
                        })
                }
                this.siteData.time = time
            },
            save() {
                if (this.uploadList.length <= 0) {
                    this.$Message.error("请上传图片")
                    this.modalLoading = false
                    return
                }
                if (this.tableData.length <= 0) {
                    this.$Message.error("请导入表单数据")
                    this.modalLoading = false
                    return
                }
                if (!this.siteData.name) {
                    this.$Message.error("请输入场地名称")
                    this.modalLoading = false
                    return
                }
                if (!this.siteData.desc) {
                    this.$Message.error("请输入场地简介")
                    this.modalLoading = false
                    return
                }
                if (!this.siteData.address) {
                    this.$Message.error("请输入场地地址")
                    this.modalLoading = false
                    return
                }
                let params = this.siteData
                params.img_url = this.uploadList[0].name
                params.table_data = {
                    data: this.tableData,
                    title: this.tableTitle,
                }
                params.annex = this.$refs.file.fileList
                saveSite(params).then(res => {
                    this.modalLoading = false
                    if (res.code === 0) {
                        this.iModal = false
                        this.$Message.success("设置成功")
                        this.$emit('refreshList');
                    }
                })
            },
            init() {
                this.baseUrl = config.baseUrl.pro
            },

        },
        watch: {
            modal: function () {
                this.iModal = this.modal
            },
            iModal: function () {
                this.$emit('bookingSettingChild', this.iModal)
            },
        },
        mounted() {
            this.uploadList = this.$refs.upload.fileList;
            this.init()
        }
    }
</script>
<style>
    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
